package com.xscha.tableforge.controller;

import com.xscha.soyue.common.core.domain.R;
import com.xscha.soyue.common.core.utils.BeanMapperUtils;
import com.xscha.tableforge.model.dto.AppDto;
import com.xscha.tableforge.model.entity.App;
import com.xscha.tableforge.model.vo.AppVo;
import com.xscha.tableforge.model.vo.PageReq;
import com.xscha.tableforge.model.vo.PageResult;
import com.xscha.tableforge.service.AppService;
import com.xscha.tableforge.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/apps")
public class AppController {

    private final AppService appService;

    @Autowired
    public AppController(AppService appService) {
        this.appService = appService;
    }

    @GetMapping("/space/{spaceId}")
    public R<List<AppVo>> getAppsBySpaceId(@PathVariable String spaceId) {
        return R.ok(BeanMapperUtils.mapAsList(appService.findAllBySpaceId(spaceId), AppVo.class));
    }
    
    @PostMapping("/space/{spaceId}/page")
    public R<PageResult<AppVo>> getAppsBySpaceIdPage(
            @PathVariable String spaceId,
            @RequestBody PageReq pageRequest) {
        PageResult<App> result = appService.findPageBySpaceId(spaceId, pageRequest);
		List<AppVo> appVos = BeanMapperUtils.mapAsList(result.getRecords(), AppVo.class);
		return R.ok(PageResult.of(appVos, result.getTotal(), result.getPageNum(), result.getPageSize()));
    }

    @GetMapping("/{id}")
    public R<AppVo> getAppById(@PathVariable String id) {
        return appService.findById(id)
                .map(app -> R.ok(BeanMapperUtils.map(app, AppVo.class)))
                .orElse(R.fail("应用不存在"));
    }

    @PostMapping
    public R<AppVo> createApp(@RequestBody AppDto appDto) {
        App app = BeanMapperUtils.map(appDto, App.class);
        App createdApp = appService.createApp(app, SecurityUtils.getUserId());
        return R.ok(BeanMapperUtils.map(createdApp, AppVo.class));
    }

    @PutMapping("/{id}")
    public R<AppVo> updateApp(@PathVariable String id, @RequestBody AppDto appDto) {
        if (!id.equals(appDto.getId())) {
            return R.fail("ID不匹配");
        }
        
        App app = BeanMapperUtils.map(appDto, App.class);
        App updatedApp = appService.updateApp(app, SecurityUtils.getUserId());
        return R.ok(BeanMapperUtils.map(updatedApp, AppVo.class));
    }

    @DeleteMapping("/{id}")
    public R<Void> deleteApp(@PathVariable String id) {
        appService.deleteApp(id, SecurityUtils.getUserId());
        return R.ok();
    }
}